package com.kwok.ssm.springmvc.handler.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CustomInterceptor implements HandlerInterceptor {

    // 进入XxxController的目标handler方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("CustomInterceptor.preHandle");
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String username = (String) request.getSession().getAttribute("username");
        if (username == null) {
            response.sendRedirect(request.getContextPath() + "/jsp/login.jsp");
            return false;
        } else {
            // return true表示拦截器放行
            return true;
        }
//  }      return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    // 进入XxxController的目标handler方法之后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("CustomInterceptor.postHandle");
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    // 整个请求完成，即视图渲染完毕之后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("CustomInterceptor.afterCompletion");
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
